<?php

namespace common\models;

use Yii;
use yii\db\Exception;
use common\helpers\Util;

/**
 * This is the model class for table "EmploymentSalary".
 */
class EmploymentSalary extends ActiveRecord {

    // @name 发放状态
    const StatusInit = 0;
    const StatusConfirm = 1;
    const StatusPaying = 2;
    const StatusSuccess = 10;
    const StatusClose = 11;
    public static $statusSelector = [
        self::StatusInit => ['title' => '待发放', 'status' => 'orange'],
        self::StatusConfirm => ['title' => '确认发薪', 'status' => 'orange'],
        self::StatusPaying => ['title' => '发放中', 'status' => 'blue'],
        self::StatusSuccess => ['title' => '发放成功', 'status' => 'green'],
        self::StatusClose => ['title' => '中止', 'status' => 'red'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['order_number', 'employment_id', 'employer_id', 'designer_id', 'paydate', 'begin', 'finish', 'hires', 'deduct'], 'required'],
            [['employment_id', 'employer_id', 'designer_id', 'paydate', 'begin', 'finish', 'hires', 'deduct', 'status', 'success_at', 'deleted_at'], 'integer'],
            [['order_number'], 'string', 'max' => 32],
            [['remark'], 'string', 'max' => 255],
        ];
    }
    /**
     * @name 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'order_number' => '订单号',
            'employment_id' => '雇佣编号',
            'employer_id' => '雇主',
            'designer_id' => '设计师',
            'paydate' => '发薪日期',
            'begin' => '计薪开始时间',
            'finish' => '计薪结束时间',
            'hires' => '薪水',
            'deduct' => '扣除',
            'status' => '状态',
            'remark' => '备注',
            'success_at' => '实际发薪日期',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * @name do some thing before save this employment salary object
     * @param $insert boolean update params
     * @return boolean
     */
//    public function beforeSave($insert)
//    {
//        // 插入前
//        if(parent::beforeSave($insert)) {
//            // 添加/修改 管理员
//            $this->admin_id = Yii::$app->admin['id'];
//        }
//        return true;
//    }

    /**
     * @name 获取user信息
     * @return \yii\db\ActiveQuery
     */
    public function getDesigner()
    {
        return $this->hasOne(User::className(), ['id' => 'designer_id']);
    }

    /**
     * @name 获取设计师账户信息
     * @return object
     */
    public function getDesignerAccount()
    {
        return $this->hasOne(UserAccount::className(), ['user_id' => 'designer_id']);
    }

    /**
     * @name 获取employer信息
     * @return \yii\db\ActiveQuery
     */
    public function getEmployer()
    {
        return $this->hasOne(User::className(), ['id' => 'employer_id']);
    }

    /**
     * @name 获取雇主账户信息
     * @return object
     */
    public function getEmployerAccount()
    {
        return $this->hasOne(UserAccount::className(), ['user_id' => 'employer_id']);
    }

    /**
     * @name 判断是否可以结算
     * @return boolean
     */
    public function canSettle()
    {
        if($this->deleted()) {
            return false;
        }
        if(in_array($this->status, [static::StatusInit])) {
            if($this->paydate <= date('Ymd', strtotime('-3 days'))) {
                return true;
            }
            return false;
        }
        if($this->paydate > date('Ymd')) {
            return false;
        }
        if(in_array($this->status, [static::StatusInit, static::StatusConfirm, static::StatusPaying])) {
            return true;
        }
        return false;
    }

    /**
     * 雇主确认发薪
     * @return boolean
     */
    public function confirm()
    {
        if( ! in_array($this->status, [static::StatusInit])) {
            return false;
        }
        $this->status = static::StatusConfirm;
        $this->updated_at = time();
        return $this->transaction(function($db) {
            if( ! $this->save()) {
                throw new Exception('change status failed');
            }
            // 记录日志
            if( ! $this->logger(['handler' => EmploymentLog::HandlerUser, 'remark' => '雇主确认发薪'])) {
                throw new \Exception('create employment salary log error');
            }
            return true;
        });
    }

    /**
     * @name 设置薪酬记录结算成功
     * @param $remark string 备注
     * @return boolean
     */
    public function success($remark = '')
    {
        if( ! $this->canSettle()) {
            return false;
        }
        $this->remark = $remark;
        $this->status = static::StatusSuccess;
        $this->success_at = time();
        $this->updated_at = time();
        $this->admin_id = Yii::$app->admin->id;
        return $this->transaction(function($db) {
            if( ! $this->save()) {
                throw new Exception('update employment salary status failed');
            }
            // 记录日志
            if( ! $this->logger(['handler' => EmploymentLog::HandlerAdmin, 'remark' => '薪酬结算完成'])) {
                throw new Exception('create employment salary log failed');
            }
            // 更新用户余额表
            if( ! $this->designerAccount->earn(bcsub($this->hires, $this->deduct))) {
                throw new \Exception('update user account error');
            }
            return true;
        });
    }

    /**
     * @name 设置薪酬记录异常关闭
     * @param $remark string 备注
     * @return boolean
     */
    public function close($remark = '')
    {
        $this->remark = $remark;
        $this->status = static::StatusClose;
        $this->updated_at = time();
        $this->admin_id = Yii::$app->admin->id;
        return $this->transaction(function($db) {
            if( ! $this->save()) {
                throw new Exception('change status failed');
            }
            // 记录日志
            if( ! $this->logger(['handler' => EmploymentLog::HandlerAdmin, 'remark' => '关闭薪酬记录'])) {
                throw new \Exception('create employment salary log error');
            }
            return true;
        });
    }

    /**
     * @name 添加日志
     * @param $param array 数据数组
     * @return boolean
     */
    public function logger($param)
    {
        $param['employment_id'] = $this->employment_id;
        return EmploymentLog::logger($param);
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function generateOrderNumber()
    {
        return strtoupper('ES'.base_convert((microtime(true) * 10000).rand(10000, 99999).rand(10000, 99999), 10, 36));
    }

    /**
     * 批量插入薪酬
     * @return boolean
     */
    public static function batchInsert($params)
    {
        if(empty($params)) {
            return false;
        }
        $columns = ['order_number', 'employment_id', 'employer_id', 'designer_id', 'paydate', 'begin', 'finish', 'hires', 'deduct', 'status', 'remark', 'created_at', 'updated_at'];
        return Util::batchInsert(static::tableName(), $columns, $params, static::getDb());
    }
}